<template>
  <div
    class="button"
    :class="{ selected: selected }"
    :style="{
      width: w,
      height: h,
      borderRadius: r,
      lineHeight: h,
      background: b,
      display: block ? 'block' : 'inline-block',
    }"
    @click="click"
    @touchstart="touchstart"
    @touchend="touchend"
    @touchcancel="touchend"
  >
    <span :style="[textStyle, {fontWeight: bold ? 'bold' : '400'}]"><slot></slot></span>
  </div>
</template>

<script>
export default {
  props: {
    // 宽度
    w: {
      type: String,
      default: "80px",
    },
    // 高度
    h: {
      type: String,
      default: "40px",
    },
    // 圆角
    r: {
      type: String,
      default: "6px",
    },
    // 背景颜色
    b: {
      type: String,
      default: "#07c160",
    },
    // 文字样式
    textStyle: Object,
    // 块级元素
    block: {
      type: Boolean,
      default: false,
    },
    // 加粗
    bold: {
      type: Boolean,
      default: false,
    },
    // 跳转的目标路由对象，同 vue-router 的 to 属性
    to: Object,
    // 跳转的链接地址
    url: String,
    // 是否禁用
    disabled: Boolean
  },
  data() {
    return {
      selected: false,
    };
  },
  methods: {
    // 开始点击
    touchstart() {
      this.selected = true;
      this.$emit("touchstart");
    },
    // 点击
    click() {
      let { to, url, disabled } = this

      if(disabled) {
        return
      }

      if((to && to.path) ||(to && to.name)) {
        this.$router.push(to);
      }else if(url) {
        window.location.href = url
      }

      this.$emit("click");
    },
    // 点击结束
    touchend() {
      this.selected = false;
      this.$emit("touchend");
    },
  },
};
</script>

<style lang="scss" scoped>
.button {
  text-align: center;
  overflow: hidden;
  color: white;
  font-size: 14px;
  user-select: none;
  box-sizing: border-box;

  &.selected {
    opacity: 0.7;
  }
}
</style>